package com.yanguilai.rabbitmqtest.send;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Component
public class NewTask {

    //    private final static String QUEUE_NAME = "hello";
    private final static String QUEUE_NAME = "task_queue";
    private final static boolean durable = true;

    private static Channel channel;

    static {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("c7formal");
        Connection connection = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    public void send(String str) {
        String msg = String.join(" ", str);
        try {
            channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
            System.out.println(" [x] Sent '" + msg + "'");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
